package com.solocredit.finance.utils.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.RelativeLayout
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.solocredit.finance.R
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.base.adapter.MullaOnItemChildClickListener
import com.solocredit.finance.base.adapter.MullaRecyclerViewAdapter
import com.solocredit.finance.base.adapter.MullaViewHolderHelper
import com.solocredit.finance.base.utils.TitleBarUtil
import com.solocredit.finance.databinding.DialogMullaCouponUseBinding
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.utils.event.MullaEventType
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/9 13:45
 * @Annotation：优惠券使用dialog
 */
class CouponUseDialog: ProDialog {
    private lateinit var binding: DialogMullaCouponUseBinding
    private var mCallback: IDialogCallback? = null
    private var couponAdapter: CouponAdapter? = null

    override fun initWindow() {
        val params = window?.attributes
        params?.width = WindowManager.LayoutParams.MATCH_PARENT
        params?.height = MyApp.app.getPhoneHeight() - TitleBarUtil.getStatusBarHeight()
        window?.attributes = params
        window?.setWindowAnimations(R.style.picker_view_slide_anim) //修改动画样式
        window?.setGravity(Gravity.BOTTOM)
    }

    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, callback: IDialogCallback?) : super(context) {
        mCallback = callback
    }

    /**
     * 设置点击回调
     */
    fun setOnClick(callback: IDialogCallback){
        this.mCallback = callback
    }

    override fun getRootView(): View {
        binding = DialogMullaCouponUseBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun initView() {
//        val topDecoration = DensityUtils.dp2px(10f)
//        binding.recyclerView.addItemDecoration(LinearSpacingItemDecoration(0,topDecoration,0,0))
        binding.recyclerView.layoutManager = LinearLayoutManager(context)
        couponAdapter = CouponAdapter(binding.recyclerView)
        binding.recyclerView.adapter = couponAdapter
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        couponAdapter?.setOnItemChildClickListener(MullaOnItemChildClickListener { _, childView, position ->
            couponAdapter?.let {
                val item = it.getItem(position)
                if (item.optBoolean("isSelect", false) || !item.optBoolean("isAvailable", false)) {
                    return@MullaOnItemChildClickListener
                }
                for (i in 0..< it.itemCount) {
                    val model = it.getItem(i)
                    if (i == position) {
                        model.put("isSelect", true)
                        continue
                    }
                    model.put("isSelect", false)
                }
                it.notifyDataSetChanged()
            }
            binding.imgUnused.setImageResource(R.mipmap.mulla_coupon_normal)
        })
    }

    override fun initListener() {
        setOnClickListener(R.id.parentLayout)
        setOnClickListener(R.id.contentLayout)
        setOnClickListener(R.id.imgClose) //关闭
        setOnClickListener(R.id.unusedLayout)
        setOnClickListener(R.id.btnConfirm)
    }

    override fun initData() {
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onViewClick(v: View?) {
        if (v?.id == R.id.contentLayout){
            return
        }
        if (v?.id == R.id.unusedLayout){
            binding.imgUnused.setImageResource(R.mipmap.mulla_coupon_selected)
            couponAdapter?.let { adapter ->
                adapter.data.forEach {
                    it.put("isSelect",false)
                }
            }
            couponAdapter?.notifyDataSetChanged()
            return
        }
        dismiss()
        when(v?.id){
            R.id.btnConfirm -> {
                if(mCallback != null){
                    mCallback?.onClick(getMullaSelectCoupon())
                }
            }
        }
    }

    /**
     * 设置优惠券列表
     */
    fun setMullaUserCouponList(couponList: ArrayList<JSONObject>){
        couponAdapter?.data = couponList
        if (getMullaSelectCoupon() == null){
            binding.imgUnused.setImageResource(R.mipmap.mulla_coupon_selected)
        } else {
            binding.imgUnused.setImageResource(R.mipmap.mulla_coupon_normal)
        }
    }

    /**
     * 获取选择的优惠券
     */
    private fun getMullaSelectCoupon(): JSONObject?{
        var obj: JSONObject? = null
        couponAdapter?.let {
            for (i in 0..< it.itemCount){
                val item = it.getItem(i)
                if (item.optBoolean("isSelect",false)){
                    obj = item
                    break
                }
            }
        }
        return obj
    }

    interface IDialogCallback {
        //按钮点击
        fun onClick(couponInfo: JSONObject?)
    }

    fun getString(strId: Int): String{
        return MyApp.app.getString(strId)
    }

    /**
     * 优惠券列表
     */
    class CouponAdapter(recyclerView: RecyclerView?) : MullaRecyclerViewAdapter<JSONObject>(recyclerView,R.layout.item_mulla_coupon_use) {

        override fun setItemChildListener(helper: MullaViewHolderHelper, viewType: Int) {
            helper.setItemChildClickListener(R.id.itemLayout) //点击Item
        }

        @SuppressLint("SetTextI18n")
        override fun fillData(helper: MullaViewHolderHelper, position: Int, model: JSONObject) {
            val couponInfo = JSONObject(model.optString("couponInfo"))
            helper.setText(R.id.textAmount,couponInfo.optString("amount"))
            helper.setText(R.id.textUnit,couponInfo.optString("currency"))
            val fullAmount = couponInfo.optString("fullAmount")
            helper.setText(R.id.textFulAmount,String.format(MyApp.app.getString(R.string.coupon_ful_amount),fullAmount))
            helper.setText(R.id.textExpiresTime,String.format(MyApp.app.getString(R.string.coupon_expires_time),model.optString("expiresTime")))

            val daysLeft = model.optInt("daysLeft")
            val textDaysLeft = helper.getTextView(R.id.textDaysLeft)
            textDaysLeft.text = "(${String.format(MyApp.app.getString(R.string.loan_repayment_days_left),daysLeft.toString())})"
            if (daysLeft <= 7){
                textDaysLeft.setTextColor(Color.parseColor("#FFFFAC25"))
            } else {
                textDaysLeft.setTextColor(Color.parseColor("#ff999999"))
            }

            val amountLayout = helper.getView<RelativeLayout>(R.id.amountLayout)
            val textCouponType = helper.getTextView(R.id.textCouponType)
            //是否可用
            if (model.optBoolean("isAvailable",false)){
                helper.setVisibility(R.id.unavailableLayout,View.GONE)
                amountLayout.setBackgroundResource(R.drawable.mulla_coupon_use_item_bg)
                textCouponType.setBackgroundResource(R.drawable.mulla_radius_fill_ffd21034_lt_rb_12)
            } else {
                helper.setVisibility(R.id.unavailableLayout,View.VISIBLE)
                helper.setText(R.id.textUnavailableReason,model.optString("unavailableReason"))
                amountLayout.setBackgroundResource(R.drawable.mulla_radius_fill_ffe1e1e1_12)
                textCouponType.setBackgroundResource(R.drawable.mulla_radius_fill_ffbebebe_lt_rb_12)
            }

            val imgUsed = helper.getImageView(R.id.imgUsed)
            if (model.optBoolean("isSelect",false)){
                imgUsed.setImageResource(R.mipmap.mulla_coupon_selected)
            } else {
                imgUsed.setImageResource(R.mipmap.mulla_coupon_normal)
            }
        }
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addMullaEventAction(MullaEventType.DIALOG.MULLA_DIALOG_COUPON_USE_SHOW)
    }

    override fun dismiss() {
        super.dismiss()
        HttpHelper.addMullaEventAction(MullaEventType.DIALOG.MULLA_DIALOG_COUPON_USE_DISMISS)
    }
}